package com.ctms.system.controller;

import com.ctms.common.utils.PageUtils;
import com.ctms.common.utils.Query;
import com.ctms.common.utils.R;
import com.ctms.common.utils.ShiroUtils;
import com.ctms.system.domain.ClassDO;
import com.ctms.system.domain.UserDO;
import com.ctms.system.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequestMapping("/class")
@Controller
public class ClassController {
    @Autowired
    ClassService classService;

    @GetMapping("")
    public String cla(Model model){
        UserDO userDO = ShiroUtils.getUser();
        String name = userDO.getName();
        int identity = userDO.getIdentity();
        String classId = classService.selectIdByName(name);
        int id = 0;
        if (classId == "" || classId == null){
            id = 0;
        }else {
            id = Integer.parseInt(classId);
        }
        System.out.println("班级id"+id);
        model.addAttribute("classId",id);
        model.addAttribute("identity",identity);
        return "sys/cla/cla";
    }

    @GetMapping("/list")
    @ResponseBody
    PageUtils list(@RequestParam Map<String,Object> params){
        Query query=new Query(params);
        //查询所有的班级基本信息
        List<ClassDO> classDOS=classService.selectAllClass(params);
        for (int i=0;i<classDOS.size();i++){
            //获取班级id
            int class_id = classDOS.get(i).getClassId();
            //通过班级id去查找这个班级的总人数
            int student = classService.countStudent(class_id);
            classDOS.get(i).setClassSize(student);
        }
        //查询出来的结果总条数
        int total=classService.count(query);
        //返回前台页面
        PageUtils pageUtils=new PageUtils(classDOS,total);
        return pageUtils;
    }

    @GetMapping("/add")
    public String add(Model model){
        return "sys/cla/add";
    }

    @PostMapping("/save")
    @ResponseBody
    R insertClass(ClassDO classDO){
        if (classService.insertClass(classDO)>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @GetMapping("/edit/{classId}")
    public String edit(Model model,@PathVariable("classId") Integer classId){
        ClassDO classDO = classService.selectById(classId);
        model.addAttribute("cla",classDO);
        return "sys/cla/edit";
    }
    @PostMapping("/update")
    @ResponseBody
    R update(ClassDO classDO){
        if (classService.updateClass(classDO)>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @PostMapping("/remove")
    @ResponseBody
    R delete(Integer classId){
        if (classService.deleteClass(classId)>0){
            return R.ok();
        }else {
            return R.error();
        }
    }
}
